TaskGrid = function(config) {

    this.columnModel = new Ext.grid.ColumnModel( {
        defaults : {
            sortable : true,
            menuDisabled : false
        },
        columns : [{
            id: 'title',
            header : 'Description',
            dataIndex : 'taskDescription',
            renderer : this.formatTitle,
            scope : this,
            sortable : false,
            menuDisabled:true
        }, {
            header : 'Task name',
            dataIndex : 'taskName',
            hidden: true
        }, {
            header : 'Process name',
            dataIndex : 'processName',
            hidden: true
        }, {
            header : 'Creation date',
            dataIndex : 'taskStartDate',
            renderer : Ext.util.Format.dateRenderer('d.m.Y H:i'),
            hidden: false
        }, {
            header : 'Due date',
            dataIndex : 'taskDueDate',
            renderer : Ext.util.Format.dateRenderer('d.m.Y H:i'),
            hidden: false
        }, {
            header: 'Actions',
            align: 'center',
            renderer: this.renderActions,
            scope:this,
            width:150,
            sortable : false,
            menuDisabled:true
        }
        ]
    });

    this.reader = new Ext.data.JsonReader({
        root : 'tasks',
        totalProperty : 'totalCount',
        id : 'taskId',
        fields : [{
            name : 'taskId'
        }, {
            name : 'taskName'
        }, {
            name : 'taskDescription'
        }, {
            name : 'taskStartDate',
            id : 'taskStartDate',
            type : 'date',
            dateFormat : 'd.m.Y H:i'
        }, {
            name : 'taskDueDate',
            type : 'date',
            dateFormat : 'd.m.Y H:i'
        }, {
            name : 'taskAssignee'
        }, {
            name : 'taskOwner'
        }, {
            name : 'processName'
        }, {
            name : 'processInstanceId'
        }, {
            name : 'processDefinitionId'
        }, {
            name : 'taskFormKey'
        }, {
            name : 'bpmn_assigned_by'
        }]
    });

    this.dataStore = new Ext.data.GroupingStore( {
        reader: this.reader,
        proxy : new Ext.data.HttpProxy( {
            method : 'GET',
            url : DISPATCHER_CONTEXT + 'task/list'
        }),
        baseParams : {
            start:0,
            limit:TASK_LIST_PAGE_SIZE
        },
        //remoteSort :true,
        sortInfo:{field: 'taskStartDate', direction: "DESC"},
        groupField:'processName'
    } );

    Ext.apply(this, {
        colModel : this.columnModel,
        store : this.dataStore,
        bbar : new Ext.PagingToolbar({
            pageSize: TASK_LIST_PAGE_SIZE,
            store: this.dataStore,
            displayInfo: true
        }),
        stripeRows : true,
        view: new Ext.grid.GroupingView({
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})',
            enableRowBody:true,
            showPreview:true,
            getRowClass : this.applyRowClass
        }),
        style: {
            height: '100%'
        },
        autoWidth : true,
        loadMask: {msg:'Loading...'},
        border : false,
        autoExpandColumn : 'title'
//        stateful : true,
//        stateId : 'grid'
    });

    this.taskTemplate = new Ext.Template([
          '<div style="float:left;">',
              '<img src="css/images/icons/task_32.png">',
          '</div>',
          '<div class="topic">',
              '<b>{0}</b>',
              '<span class="author">Creation date: {3}</span></br>',
              '<span class="author">Due date: {4}</span></br>',
              '<span class="author">Created by: {2}</span></br>',
          '</div>'
    ]);
    this.taskTemplate.compile();


    TaskGrid.superclass.constructor.apply(this, [ config ]);

    this.subscribe('taskSelected', function(node) {
        this.taskKey = node.attributes.id;
        this.dataStore.setBaseParam('condition', node.attributes.id);
        if (this.taskKey) {
            this.dataStore.load();
        }
    }, this);

    this.subscribe('taskRefresh', function() {
        if (this.taskKey) {
            this.dataStore.load();
        }
    }, this);

};

Ext.extend(TaskGrid, Ext.grid.GridPanel, {

    // within this function "this" is actually the GridView
    applyRowClass: function(record, rowIndex, p, ds) {
        if (this.showPreview) {
            var xf = Ext.util.Format;
            p.body = '<p>Description: ' + xf.ellipsis(xf.stripTags(record.data.taskDescription), 200) + '</p>';
            return 'x-grid3-row-expanded';
        }
        return 'x-grid3-row-collapsed';
    },

    formatTitle: function(value, p, record) {
        return this.taskTemplate.apply([
                                        record.data.taskName,
                                        record.data.taskDescription,
                                        record.data.bpmn_assigned_by,
                                        Ext.util.Format.date(record.data.taskStartDate, 'd.m.Y H:i'),
                                        Ext.util.Format.date(record.data.taskDueDate, 'd.m.Y H:i')]);
    },

    createGridButton: function(config, id, record, grid) {
        Ext.applyIf(config,{
            text: null
            ,iconCls: 'button-navigation-refresh'
            ,cls:'button-grid-action'
            ,scale:'medium'
            ,handler : function(btn, e) {
                alert("Button clicked!");
            }
            ,listeners: {
                click: function(button, event) {
                    grid.getSelectionModel().selectRecords([record], false);
                }
            }

        });
        new Ext.Button(config).render(document.body, id);
    },

    renderActions: function(value, id, r) {
        var id = Ext.id();
        if (r.data.taskAssignee) {
            if (r.data.taskFormKey) {
                this.createGridButton.defer(1, this, [{
                    text:'Complete form',
                    iconCls:'button-complete-form',
                    handler: this.completeFormHandler,
                    scope:this
                }, id, r, this]);
            }
            else {
                this.createGridButton.defer(1, this, [{
                    text:'Complete',
                    iconCls:'button-complete',
                    handler: this.completeHandler,
                    scope:this
                }, id, r, this]);
            }
        }
        else {
            this.createGridButton.defer(1, this, [{
                text:'Claim',
                iconCls:'button-claim',
                handler: this.claimHandler,
                scope:this
            }, id, r, this]);
        }
        return('<div id="' + id + '"></div>');
    },

    editTemplateHandler: function (btn, e) {
        var s = this.getSelectionModel();
        var r = s.getSelected();
        var taskId = r.get('taskId');
        Ext.Ajax.request({
            url : 'mvc/task/form',
            method : 'GET',
            params : {
                taskId : taskId,
                formXtype : 'editTemplateForm'
            },
            success :function(response, opts){
                var obj = Ext.decode(response.responseText);
                obj.width=365;
                if (obj.formConfig === undefined) {
                    obj.formConfig = {};
                }
                obj.formConfig.labelWidth=95;
                var formWindow = Ext.ComponentMgr.create(obj);
                formWindow.show();
            }
        });
    },

    claimHandler: function (btn, e) {
        var s = this.getSelectionModel();
        var r = s.getSelected();
        var taskId = r.get('taskId');
        Ext.Ajax.request({
            url : DISPATCHER_CONTEXT + 'task/claim',
            method : 'POST',
            params : {
                taskId : taskId
            },
            success :function(response, opts){
                this.publish('taskRefresh');
            },
            scope : this
        });
    },

    completeFormHandler: function () {
        var s = this.getSelectionModel();
        var r = s.getSelected();
        Ext.Ajax.request({
            url : DISPATCHER_CONTEXT + 'task/form',
            method : 'GET',
            params : {
            taskId : r.get('taskId')
            },
            success :function(response, opts){
                var obj = Ext.decode(response.responseText);
                if (obj.formConfig === undefined) {
                    obj.formConfig = {};
                }
                obj.taskId = r.get('taskId');
                var formWindow = Ext.ComponentMgr.create(obj);
                formWindow.show();
            }
        });
    }

});

Ext.reg('taskGrid', TaskGrid);